// JIT Timing Test Case
// This test case is designed to trigger JIT compilation and test the timing functionality

function hotFunction(x) {
    // This function will be called repeatedly to trigger JIT compilation
    let sum = 0;
    for (let i = 0; i < 1000; i++) {
        sum += x * i;
    }
    return sum;
}

function complexCalculation() {
    // Complex calculation that should trigger multiple optimization passes
    let result = 0;
    for (let j = 0; j < 100; j++) {
        for (let i = 0; i < 10000; i++) {
            result += Math.sin(i) * Math.cos(j);
        }
    }
    return result;
}

function createObjects() {
    // Object creation and manipulation
    const objects = [];
    for (let i = 0; i < 1000; i++) {
        objects.push({
            id: i,
            value: i * 2,
            calculate: function() { return this.value * Math.random(); }
        });
    }
    return objects;
}

function stringOperations() {
    // String operations that might trigger different optimizations
    let longString = "";
    for (let i = 0; i < 1000; i++) {
        longString += "test" + i + " ";
    }
    return longString.length;
}

function arrayOperations() {
    // Array operations
    const arr = [];
    for (let i = 0; i < 10000; i++) {
        arr.push(i);
    }
    
    // Various array methods
    const mapped = arr.map(x => x * 2);
    const filtered = mapped.filter(x => x % 3 === 0);
    const reduced = filtered.reduce((acc, val) => acc + val, 0);
    
    return reduced;
}

function mixedWorkload() {
    // Mixed workload to test different JIT optimization passes
    let total = 0;
    
    // Warm up the JIT compiler
    for (let i = 0; i < 100000; i++) {
        total += hotFunction(i % 100);
    }
    
    // Trigger more complex optimizations
    total += complexCalculation();
    
    // Test object and string optimizations
    const objects = createObjects();
    for (const obj of objects) {
        total += obj.calculate();
    }
    
    total += stringOperations();
    total += arrayOperations();
    
    return total;
}

// Main execution
function main() {
    console.log("Starting JIT timing test...");
    
    const startTime = Date.now();
    
    // Run the test multiple times to ensure JIT compilation
    let finalResult = 0;
    for (let run = 0; run < 10; run++) {
        console.log(`Run ${run + 1}/10`);
        finalResult += mixedWorkload();
    }
    
    const endTime = Date.now();
    const duration = endTime - startTime;
    
    console.log(`Test completed in ${duration}ms`);
    console.log(`Final result: ${finalResult}`);
    console.log("JIT timing data should be available in compiler logs");
}

// Execute the test
main();